package com.example.administrator.wallet.view.activity;

import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ActivityUtils;
import com.example.administrator.wallet.MainActivity;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.adapter.RecoveryAdapter;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.RecoveryBean;
import com.example.administrator.wallet.utils.AESUtils;
import com.example.administrator.wallet.utils.ListDataSave;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ExtendedKey;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ValidationException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip39.SeedCalculator;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.AddressIndex;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.BIP44;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.CoinPairDerive;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.Base58;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.Base64;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.BitcoinTest;
import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.Ethereum;

public class RecoveryActivity extends BaseActivity {


    @Bind(R.id.finish_img)
    ImageButton finishImg;
    @Bind(R.id.view_title)
    TextView viewTitle;
    @Bind(R.id.saoyisao)
    ImageButton saoyisao;
    @Bind(R.id.activity_recovery)
    LinearLayout activityRecovery;
    @Bind(R.id.iGridView)
    GridView iGridView;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.again_password)
    EditText againPassword;
    @Bind(R.id.select)
    ImageView select;
    @Bind(R.id.submit)
    Button submit;
    @Bind(R.id.zhujici_edit)
    EditText zhujiciEdit;
    private List<Fragment> datas;
    private List<String> fragment_title;
    private String pst;
    private String again_pst;
    private int count;
    private List<String> zhujici;
    private RecoveryAdapter adapter;
    private int adapter_size = 1;
    private String[] strings;
    private List<String> mDatas = new ArrayList<>();
    private String mEtherAddress;
    private EthECKeyPair mEtherKeyPair;
    private BitCoinECKeyPair mBitcoinKeyPair;
    private String mBitcoinAddress;
    private String mBitcoinPrivateKey;
    private String mBitcoinPublicKey;
    private String mEtherPrivateKey;
    private String mEtherPublicKey;

    @Override
    public void init() {

        pst = password.getText().toString().trim();
        again_pst = againPassword.getText().toString().trim();
        ListDataSave dataSave = new ListDataSave(this, "wallet");
        zhujici = dataSave.getDataList("zhujici");

        finishImg.setVisibility(View.VISIBLE);
        viewTitle.setText(R.string.recovery);
        setStatuColor();
        initData();
        initAdapter();
        initListener();


    }

    private void initListener() {
        zhujiciEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String s = charSequence.toString();

                if (s.length() > 0) {
                    String c1 = s.substring(s.length() - 1);
                    if (c1.equals(" ")) {
                        setEditTextInhibitInputSpace(zhujiciEdit);
                    } else {
                        setEditTextInputSpace(zhujiciEdit);
                    }
                }

                strings = s.split(" ");
//                zhujiciEdit.setSelection(zhujiciEdit.getText().toString().length());

                List<String> list = new ArrayList<String>();
                if (strings.length == 12) {
                    list.clear();
                    for (int i3 = 0; i3 < strings.length; i3++) {
                        list.add(strings[i3]);
                    }
                    setEditTextInhibitInputSpace(zhujiciEdit);
                    OnClicks();

                }
                ListDataSave wallet = new ListDataSave(RecoveryActivity.this, "wallet");
                wallet.setDataList("zhujici", list);
                adapter = new RecoveryAdapter(RecoveryActivity.this, strings);
                iGridView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                Log.e("TAG---adapter", adapter.getCount() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString();
                int len = editable.toString().length();
                if (len > 1 && text.startsWith(" ")) {
                    editable.replace(0, 1, "");
                }
            }
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                pst = charSequence.toString();
                OnClicks();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        againPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                again_pst = charSequence.toString();
                OnClicks();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void initAdapter() {


        if (strings == null) {
            adapter = new RecoveryAdapter(this, null);
        } else {
            adapter = new RecoveryAdapter(this, strings);
        }
        iGridView.setAdapter(adapter);


    }

    public void OnClicks() {
        if (strings != null) {
            if (select.isSelected() && !(pst.equals("")) && !(again_pst.equals("")) && strings.length == 12) {
                submit.setSelected(true);
                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        for (int i3 = 0; i3 < strings.length; i3++) {
                            mDatas.add(strings[i3]);
                        }
                        final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
                        if (pst.equals(again_pst)) {
                            String iPst = Base58.encode(pst.getBytes());
                            SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "log", iPst);
                            SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "count", 3);
                            byte[] seed = new SeedCalculator().calculateSeed(mDatas, "");
                            try {
                                ExtendedKey extendedKey = ExtendedKey.create(seed);
                                ECKeyPair master = (ECKeyPair) extendedKey.getMaster();
                                AddressIndex index_Ethereum = BIP44.m().purpose44()
                                        .coinType(Ethereum)
                                        .account(0)
                                        .external()
                                        .address(0);
                                AddressIndex index_Bitcoin = BIP44.m().purpose44()
                                        .coinType(BitcoinTest)
                                        .account(0)
                                        .external()
                                        .address(0);
                                CoinPairDerive pairDerive = new CoinPairDerive(extendedKey);
                                mEtherKeyPair = (EthECKeyPair) pairDerive.derive(index_Ethereum);
                                mBitcoinKeyPair = (BitCoinECKeyPair) pairDerive.derive(index_Bitcoin);
                                mBitcoinAddress = mBitcoinKeyPair.getAddress();
                                mBitcoinPrivateKey = mBitcoinKeyPair.getPrivateKey();
                                mBitcoinPublicKey = mBitcoinKeyPair.getPublicKey();
                                mEtherPrivateKey = mEtherKeyPair.getPrivateKey();
                                mEtherPublicKey = mEtherKeyPair.getPublicKey();
                                mEtherAddress = mEtherKeyPair.getAddress();

                                String secretKey = AESUtils.generateSecretKey();
                                String bitcoinKey = AESUtils.encrypt(mBitcoinPrivateKey, secretKey);
                                String ethcoinKey = AESUtils.encrypt(mEtherPrivateKey, secretKey);

                                String mEtherEncode = Base64.encode(mEtherAddress.getBytes());
                                String mBitcoinEncode = Base64.encode(mBitcoinAddress.getBytes());
                                String mEthPrivateKey = Base64.encode(mEtherPrivateKey.getBytes());
                                String mBtcPrivateKey = Base64.encode(mBitcoinPrivateKey.getBytes());

                                String s = Base64.encode(mBitcoinKeyPair.getRawPrivateKey());

                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "bit_raw", s);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "eth_private-", mEtherPrivateKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "bit-", mBitcoinPublicKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "btc_private-", mBitcoinPrivateKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "eth", mEtherEncode);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "bit", mBitcoinEncode);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "eth_private", ethcoinKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "secretKey", secretKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "btc_private", bitcoinKey);
                                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "master", new String(seed));
                                mRequestAddress(reqequestManager);
                            } catch (ValidationException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(RecoveryActivity.this, R.string.two_pst_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } else {
                submit.setSelected(false);
                submit.setOnClickListener(null);
            }
        }
    }

    private void mRequestAddress(IRequestManager reqequestManager) {
         /*let s = "\x18Bitcoin Signed Message:\n"*/
        String mBitcoinMsg = "123456";
        String mEtherMsg = "123";
/*        String m = "\u0019Ethereum Signed Message:\n" + mEtherMsg.length() + mEtherMsg;
        String b = "\\x18Bitcoin Signed Message:\n" + mBitcoinMsg;
        byte[] bytes = KECCAK256.keccak256(b.getBytes()); //SHA256.doubleSha256(("Bitcoin Signed Message:" + mBitcoinMsg).getBytes());
        byte[] digest = KECCAK256.keccak256(m.getBytes());*/
//        String mBitcoinSigntree = mBitcoinKeyPair.signBTC(bytes).toString();
/*        Log.e("TAG---Bit", mBitcoinSigntree);
        Log.e("TAG---M", mEtherAddress);
        Log.e("TAG---M", mBitcoinAddress);
        ECDSASignature s = mEtherKeyPair.sign(digest);
        String ss = s.toHex();
        Log.e("TAG---ETH", ss);*/
        reqequestManager.httpPost(Api.BaseUrl + Api.Zhujici, Api.getZhujici(mEtherMsg, "123",  "0x" + mEtherAddress,mBitcoinAddress, mBitcoinMsg, "123"), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                RecoveryBean recoveryBean = gson.fromJson(Response, RecoveryBean.class);
                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "token", recoveryBean.getData().getAccess_token());
                SharedPrefsUtil.putValue(RecoveryActivity.this, "wallet", "head_img", recoveryBean.getData().getHead_portrait());
                ActivityUtils.startActivity(RecoveryActivity.this, MainActivity.class);
                finish();
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (strings != null) {
            if (strings.length <= 12) {
                showSoftInputFromWindow(zhujiciEdit);
            }
        }
        OnClicks();
    }

    /**
     * EditText获取焦点并显示软键盘
     */
    public void showSoftInputFromWindow(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    /**
     * 禁止EditText输入空格
     *
     * @param editText
     */

    public static void setEditTextInhibitInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return "";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }

    /**
     * 允许EditText输入空格
     *
     * @param editText
     */
    public static void setEditTextInputSpace(EditText editText) {
        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" ")) {
                    return " ";
                } else {
                    return null;
                }
            }
        };
        editText.setFilters(new InputFilter[]{filter});
    }



/*        mViewPagerAdapter adapter = new mViewPagerAdapter(getSupportFragmentManager(), datas, fragment_title);
        mViewPager.setAdapter(adapter);
        mXtab.setupWithViewPager(mViewPager);

        mXtab.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                CharSequence text = tab.getText();
                if(text.equals("官方钱包")){
                    saoyisao.setVisibility(View.VISIBLE);
                }else{
                    saoyisao.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });*/


    private void initData() {

//        datas = new ArrayList<>();
//        datas.clear();
//        datas.add(new AccountWordsFragment());
//        datas.add(new OfficialFragment());
//        datas.add(new PrivateKeyFragment());
//        fragment_title = new ArrayList<>();
//        fragment_title.clear();
//        fragment_title.add("助记词");
//        fragment_title.add("官方钱包");
//        fragment_title.add("私钥");


    }

    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size())
            return false;
        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i)))
                return false;
        }
        return true;
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_recovery;
    }


    @OnClick({R.id.finish_img, R.id.saoyisao, R.id.select, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_img:
                finish();
                break;
            case R.id.saoyisao:
                break;
            case R.id.select:
                if (select.isSelected()) {
                    select.setSelected(false);
                } else {
                    select.setSelected(true);
                }
                OnClicks();
                break;
            case R.id.submit:

                break;
        }
    }

}
